<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form size="mini" :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="角色" @keyup.enter.native="searchHandle" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" :loading="searchForm.loading" @click="searchHandle">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-plus" @click="insertHandle()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" :disabled="dataTable.idSelection.length === 0" @click="deleteHandle()">删除</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <el-table v-loading="dataTable.loading" element-loading-text="加载中，请稍后..." size="mini" border fit highlight-current-row :data="dataTable.roles" @selection-change="idSelectionHandle">
      <el-table-column prop="id" type="selection" fixed />
      <el-table-column label="名称" prop="name" />
      <el-table-column label="描述" prop="description" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.status | statusFilter">
            {{ scope.row.status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" :formatter="createTimeFormatHandle" />
      <el-table-column label="更新时间" align="center" :formatter="updateTimeFormatHandle" />
      <el-table-column label="操作" fixed="right" align="center" width="290">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="updateHandle(scope.row)">编辑</el-button>
          <el-button type="warning" size="mini" @click="assignHandle(scope.row)">授权</el-button>
          <el-button type="danger" size="mini" @click="deleteHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination :total="searchForm.total" :current-page="searchForm.currentPage" :page-size="searchForm.pageSize" @size-change="pageSizeChangeHandle" @current-change="currentPageChangeHandle" />
    <!-- 添加角色 -->
    <role-insert :visible.sync="insertVisible" @reloadTable="searchHandle" />
    <!-- 更新角色 -->
    <role-update :visible.sync="updateVisible" :row-data="rowData" @reloadTable="searchHandle" />
    <!-- 角色授权 -->
    <role-auth :visible.sync="authVisible" :role-id="roleId" reload-table="searchHandle" />
  </div>
</template>

<script>
import moment from 'moment'
import Pagination from './../../components/Pagination'
import RoleInsert from './components/role-insert'
import RoleAuth from './components/role-authorize'
import RoleUpdate from './components/role-update'
export default {
  components: {
    'pagination': Pagination,
    'role-insert': RoleInsert,
    'role-auth': RoleAuth,
    'role-update': RoleUpdate
  },
  filters: {
    statusFilter(status) {
      const statusMap = { 0: 'success', 1: 'gray' }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusTextMap = { 0: '启用', 1: '停用' }
      return statusTextMap[status]
    }
  },
  data() {
    return {
      searchForm: {
        loading: false,
        name: '',
        // 分页字段（父子组件都会用到）
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dataTable: {
        loading: false,
        roles: null,
        idSelection: []
      },
      // 子组件使用
      insertVisible: false,
      updateVisible: false,
      authVisible: false,
      assignVisible: false,
      rowData: null,
      roleId: ''
    }
  },
  created() {
    this.dataTableHandle()
  },
  methods: {
    dataTableHandle() {
      this.dataTable.loading = true
      this.searchForm.loading = true
      this.http.get('/roles', this.searchForm, false).then((response) => {
        this.dataTable.loading = false
        this.searchForm.loading = false
        // 表格数据
        this.dataTable.roles = response.data
        // 数据总条数
        this.searchForm.total = response.total
      }).catch(() => {
        this.dataTable.loading = false
        this.searchForm.loading = false
      })
    },
    createTimeFormatHandle(row) {
      return moment(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    updateTimeFormatHandle(row) {
      return moment(row.updateTime).format('YYYY-MM-DD HH:mm:ss')
    },
    searchHandle() {
      this.searchForm.currentPage = 1
      this.searchForm.pageSize = 20
      this.dataTableHandle()
    },
    pageSizeChangeHandle(val) {
      this.searchForm.pageSize = val
      this.dataTableHandle()
    },
    currentPageChangeHandle(val) {
      this.searchForm.currentPage = val
      this.dataTableHandle()
    },
    idSelectionHandle(val) {
      this.dataTable.idSelection = val
    },
    insertHandle() {
      this.insertVisible = true
    },
    updateHandle(row) {
      this.updateVisible = true
      this.rowData = row
    },
    authHandle(row) {
      this.authVisible = true
      this.roleId = row.id
    },
    assignHandle(row) {
      this.assignVisible = true
      this.roleId = row.id
    },
    deleteHandle(row) {
      // make
      let ids = ''
      this.dataTable.idSelection.forEach(item => {
        ids = ids + item.id + ','
      })
      if (row) {
        ids = row.id
      }
      // ajax
      // this.ComponentUtils.confirm().then(() => {
      //   this.AjaxUtils.delete('/role/deleteRole', { ids: ids }, true).then((response) => {
      //     if (response.code === 0) {
      //       this.searchHandle()
      //     }
      //   }).catch(() => {
      //   })
      // }).catch(() => {
      // })
      // 方案2 TODO 代码臃肿 需要封装
      this.$confirm('确定执行此操作吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // ajax
            instance.confirmButtonLoading = true
            this.http.delete('/role/deleteRole', { ids: ids }, true).then((response) => {
              if (response.code === 0) {
                instance.confirmButtonLoading = false
                done()
                this.searchHandle()
              }
            }).catch(() => {
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      }).then(() => {
        console.log('点了确定')
      }).catch(() => {
        console.log('点了取消')
      })
    }
  }
}
</script>
